<template>
  <div style="display: none">
    <iframe :src="fileSrc_" frameborder="0"></iframe>
  </div>
</template>

<script>
export default {
  props: ['fileSrc'],
  name: "iframeDown",
  data() {
    return {
      fileSrc_: '',
      file_can_down:['zip','rar','docx','doc','xlsx','xls', 'pdf'],
      file_preview:['jpeg','png','jpg']
    }
  },
  destroyed: function () {
    this.fileSrc_ = ''
  },
  watch:{
    fileSrc(val){
      if(val){
        this.fileSrc_ = ''
        let a = val.src.split('.')
        let type_ = a[a.length-1]
        if(this.file_can_down.indexOf(type_)!==-1){
          this.fileSrc_ = `${document.domain}${val.src}`
          console.log('this.fileSrc_=====>', this.fileSrc_)
        }else if(this.file_preview.indexOf(type_)!==-1){
          this.downloadIamge()
        }else{
          this.$confirm(`该文件不可下载，文件${val}`, '提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'warning'
          }).then(() => {
          }).catch(() => {
          });
        }
      }
    }
  },
  created() {
    console.log('this.fileSrc:', this.fileSrc)
    if(this.fileSrc){
      let val = this.fileSrc
      this.fileSrc_ = ''
      let a = val.src.split('.')
      let type_ = a[a.length-1]
      if(this.file_can_down.indexOf(type_)!==-1){
        this.fileSrc_ = `${this.$BASE_URL}${val.src}`
        console.log('this.fileSrc_=====>', this.fileSrc_)
      }else if(this.file_preview.indexOf(type_)!==-1){
        this.downloadIamge()
      }else{
        this.$confirm(`该文件不可下载，文件${val}`, '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        }).then(() => {
        }).catch(() => {
        });
      }
    }
  },
  methods: {
    downloadIamge() { // 下载图片地址和图片名
      console.log('this.fileSrc:',this.fileSrc)
      let image = new Image()// 解决跨域 Canvas 污染问题
      let this_ = this
      image.setAttribute('crossOrigin', 'anonymous')
      image.onload = function () {
        let canvas = document.createElement('canvas')
        canvas.width = image.width
        canvas.height = image.height
        let context = canvas.getContext('2d')
        context.drawImage(image, 0, 0, image.width, image.height)
        let url = canvas.toDataURL('image/png') // 得到图片的base64编码数据
        let a = document.createElement('a') // 生成一个a元素
        let event = new MouseEvent('click') // 创建一个单击事件
        a.download = this_.fileSrc.name || '任务附件' // 设置图片名称
        a.href = url // 将生成的URL设置为a.href属性
        a.dispatchEvent(event) // 触发a的单击事件
      }
      image.src = `${this.fileSrc.src}`
    }
  }
}
</script>

<style scoped>

</style>
